<template>
  <GGDialog title="选择商品" :visible.sync="visible">
    <el-card shadow="never">
      <el-form inline>
        <el-form-item label="商品名称">
          <el-input
            placeholder="请输入商品名称"
            size="small"
            v-model="searchParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品分类">
          <GGTreeSelect
            v-model="category"
            :treeData="treeData"
            :defaultProps="{
              children: 'children',
              label: 'name',
            }"
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="searchParams.createTime"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="search"
          >
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" size="small" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" v-loading="loading" rowKey="id" class="mb-20">
        <el-table-column label="#" width="50">
          <template v-slot="{ row }">
            <el-radio
              v-model="selectPicUrl"
              @input="handleRadio"
              :label="row.picUrl"
            >
              <div></div>
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column
          label="商品编号"
          prop="id"
          align="center"
        ></el-table-column>
        <el-table-column label="商品图片" align="center">
          <template v-slot="{ row }">
            <el-image class="spu-img" :src="row.picUrl"></el-image>
          </template>
        </el-table-column>
        <el-table-column
          label="商品名称"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          label="商品分类"
          align="center"
          :formatter="handleCategoryFormatter"
        ></el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchParams.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="searchParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        class="flex-end"
      >
      </el-pagination>
    </el-card>
  </GGDialog>
</template>

<script>
import { getProductCategoryList } from "@/api/mall/product/category";
import { getSpuPage } from "@/api/mall/product/spu";

export default {
  name: "SkuSelectForm",
  data() {
    return {
      visible: false,
      searchParams: {
        pageNo: 1,
        pageSize: 5,
        name: "",
        tabType: 0,
        categoryId: "",
        createTime: [],
      },
      total: 0,
      list: [],
      loading: false,
      treeData: [], // 处理后分类数据
      categoryList: [], // 原始分类数据（未分组前）
      category: {},

      selectPicUrl: "",
    };
  },
  methods: {
    open() {
      this.visible = true;
    },
    close() {
      this.visible = false;
    },
    // 分页功能
    handleSizeChange(pageSize) {
      this.searchParams.pageSize = pageSize;
      this.getList();
    },
    handleCurrentChange(pageNo) {
      this.searchParams.pageNo = pageNo;
      this.getList();
    },

    // 根据parentId对元素进行分组
    groupByParentId(data) {
      // const group = {};

      // data.forEach((item) => {
      //   if (group[item.parentId]) {
      //     group[item.parentId].push(item);
      //   } else {
      //     group[item.parentId] = [item];
      //   }
      // });

      // return group;

      return data.reduce((p, c) => {
        if (p[c.parentId]) {
          p[c.parentId].push(c);
        } else {
          p[c.parentId] = [c];
        }
        return p;
      }, {});
    },
    // 处理数据
    handleTreeData(data) {
      // 一级分类数据
      const treeData = data[0];

      // 对一级分类数据遍历
      treeData.forEach((tree) => {
        // 去找key === id的元素
        const children = data[tree.id];
        // 将得到数组添加到元素children上
        tree.children = children;
      });

      return treeData;
    },
    // 获取商品分类列表数据
    async getCategoryList() {
      const res = await getProductCategoryList();

      this.categoryList = res.data;
      // 1. 将数组按照 parentId 进行分组 --> { 0: [], 15: [xxx], ... }
      const data = this.groupByParentId(res.data);
      // 2. 提取 key: 0 的数组（一级分类），对这个数组进行遍历
      // 3. 遍历元素id，去上面对象找key === id的元素，将得到数组添加到元素children上
      const treeData = this.handleTreeData(data);
      // 更新数据
      this.treeData = treeData;
    },
    // 获取spu列表
    async getList() {
      this.loading = true;
      const { data } = await getSpuPage({
        ...this.searchParams,
        categoryId: this.category.id,
      });
      this.total = data.total;
      this.list = data.list;
      this.loading = false;
    },
    // 处理分类名称
    handleCategoryFormatter(row) {
      return this.categoryList.find((cate) => cate.id === row.categoryId).name;
    },
    // 搜索
    search() {
      this.searchParams.pageNo = 1;
      this.getList();
    },
    // 重置
    reset() {
      this.searchParams = {
        pageNo: 1,
        pageSize: 5,
        name: "",
        tabType: 0,
        categoryId: "",
        createTime: [],
      };
      this.getList();
    },

    handleRadio(picUrl) {
      this.close();
      this.$emit("success", picUrl);
    },
  },
  mounted() {
    this.getCategoryList();
    this.getList();
  },
};
</script>

<style scoped>
.spu-img {
  width: 50px;
  height: 50px;
}
</style>
